package com.walter.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import java.util.UUID;

import static com.walter.common.constants.CommonConstant.TRACE_ID;

/**
 * @author Walter
 * @date 2025/1/21 下午4:13
 **/
public class TraceIdUtil {

    public static void setTraceId(String traceId) {
        if (StringUtils.isBlank(traceId)) {
            traceId = createTraceId();
        }
        MDC.put(TRACE_ID, traceId);
    }
    public static void setTraceId() {
        String traceId = MDC.get(TRACE_ID);
        if (StringUtils.isNotBlank(traceId)) {
            return;
        }
        setTraceId(createTraceId());
    }

    public static String getTraceId() {
        String traceId = MDC.get(TRACE_ID);
        return StringUtils.isBlank(traceId) ? createTraceId() : traceId;
    }
    public static String createTraceId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    public static void remove(){
        MDC.remove(TRACE_ID);
    }
}
